<script setup>
import { ref, onMounted, watch } from 'vue'
import { ArrowLeft } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()

const cartData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)
const totalPrice = ref(0)

const getCart = async (status) => {
    const res = await request.get('/cart', {
        params: {
            id: JSON.parse(localStorage.getItem('loginStore')).id,
            page: currentPage.value,
            pageSize: pageSize.value,
            status: status
        }
    })
    console.log(res)
    total.value = res.data.data.total
    cartData.value = res.data.data.record
    totalPrice.value = res.data.data.record.reduce((sum, item) => sum + item.price * item.num, 0)
}

const handleSizeChange = (val) => {
    pageSize.value = val

}
const handleCurrentChange = (val) => {
    currentPage.value = val
}

const handleChange = async (val, id) => {
    await request.post('/upcart', {
        id: id,
        num: val
    })
    ElMessage({
        type: 'success',
        message: '修改成功'
    })
    getCart(activeIndex.value)
    totalPrice.value = res.data.data.record.reduce((sum, item) => sum + item.price * item.num, 0)
}

const delCart = async (id) => {
    await request.delete('/cart', {
        params: {
            id
        }
    })
    ElMessage({
        type: 'success',
        message: '删除成功'
    })
    getCart(activeIndex.value)
    totalPrice.value = res.data.data.record.reduce((sum, item) => sum + item.price * item.num, 0)
}

onMounted(() => {
    getCart(0)
})

watch([currentPage, pageSize], () => {
    getCart(activeIndex.value)
})

const cartForm = ref({
    name: '',
    address: '',
    phone: ''
})

const dialog = ref(false)

const show = () => {
    if (cartData.value == '') {
        ElMessage({
            type: 'warning',
            message: '购物车为空'
        })
        return
    }
    dialog.value = true
}

const upOrder = async () => {
    await request.post('/order', {
        userId: JSON.parse(localStorage.getItem('loginStore')).id,
        name: cartForm.value.name,
        address: cartForm.value.address,
        phone: cartForm.value.phone
    })
    ElMessage({
        type: 'success',
        message: '下单成功'
    })
    cartForm.value = ref({
        name: '',
        address: '',
        phone: ''
    })
    dialog.value = false
    getCart(0)
}

const goBack = () => {
    router.go(-1)
}

const activeName = ref('first')

const activeIndex = ref(0)

const handleClick = () => {
    if (activeIndex.value == 0) {
        activeIndex.value = 1
        cartData.value = []
        getCart(1)
        return
    }
    if (activeIndex.value == 1) {
        activeIndex.value = 0
        cartData.value = []
        getCart(0)
        return
    }

    // getCart(activeIndex.value)
}
</script>
<template>
    <el-page-header :icon="ArrowLeft" class="header" @click="goBack">
        <template #content>
            <span class="text-large font-600 mr-3"> 购物车 </span>
        </template>
    </el-page-header>
    <el-tabs v-model="activeName" type="border-card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="未付款" name="first">
            <div class="main">
                <div class="item" v-for="item in cartData" :key="item.id" v-if="cartData != ''">
                    <div class="left">
                        <img :src="item.image" alt="" class="img">
                    </div>
                    <div class="mid">
                        <div class="name">{{ item.bookname }}</div>
                        <div class="author">{{ item.author }}<span>&nbsp;&nbsp;&yen;{{ item.price.toFixed(2) }}</span>
                        </div>
                    </div>
                    <div class="right">
                        <el-button type="danger" @click="delCart(item.id)">删除商品</el-button>
                        <el-input-number v-model="item.num" :min="1"
                            @change="((val) => { handleChange(val, item.id) })" />
                    </div>
                </div>
                <div class="empty" v-else>购物车为空</div>
                <div class="foot">
                    <div class="total">
                        <el-button type="primary" class="post" @click="show">提交订单</el-button>
                    </div>
                    <div class="price">
                        总价格&nbsp;&yen;{{ totalPrice.toFixed(2) }}
                    </div>
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper"
                        :total="total" class="page">
                    </el-pagination>
                </div>
            </div>
        </el-tab-pane>
        <el-tab-pane label="已付款" name="second">
            <div class="main">
                <div class="item" v-for="item in cartData" :key="item.id" v-if="cartData != ''">
                    <div class="left">
                        <img :src="item.image" alt="" class="img">
                    </div>
                    <div class="mid">
                        <div class="name">{{ item.bookname }}</div>
                        <div class="author">{{ item.author }}<span>&nbsp;&nbsp;&yen;{{ item.price.toFixed(2) }}</span>
                        </div>
                    </div>
                    <div class="right">
                        <el-button type="danger" @click="delCart(item.id)">删除商品</el-button>
                        <el-input-number v-model="item.num" :min="1" :disabled="true"
                            @change="((val) => { handleChange(val, item.id) })" />
                    </div>
                    <div class="last">
                        <div>收货人：{{ item.name }}</div>
                        <div>收货手机：{{ item.phone }}</div>
                        <div>收货地址：{{ item.address }}</div>
                        <div>下单时间：{{ item.time }}</div>
                    </div>
                </div>
                <div class="empty" v-else>购物车为空</div>
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper"
                    :total="total" class="page">
                </el-pagination>
            </div>

        </el-tab-pane>
    </el-tabs>
    <el-dialog v-model="dialog" title="订单地址" width="500">
        <el-form :model="cartForm" label-position="right">
            <el-form-item label="收获姓名">
                <el-input v-model="cartForm.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="收货地址">
                <el-input v-model="cartForm.address" autocomplete="off" />
            </el-form-item>
            <el-form-item label="收货手机">
                <el-input v-model="cartForm.phone" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog = false">取消</el-button>
                <el-button type="primary" @click="upOrder">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style scoped lang="scss">
.header {
    width: 1400px;
    margin: 0 auto;
    color: red;
    padding: 18px;
}

.demo-tabs {
    width: 1400px;
    margin: 0 auto;
}

.main {
    width: 1400px;
    margin: 0 auto;
    min-height: 520px;
    margin-bottom: 18px;

    .last {
        color: aqua;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        font-size: 18px;
    }


    .foot {
        display: flex;
        padding: 0 28px;
        height: 38px;
        line-height: 38px;
        justify-content: space-between;

        .page {
            float: right;
        }

        .price {
            color: red;
        }
    }

    .item {
        display: flex;
        width: 1400px;
        height: 160px;
        border-bottom: 2px solid #BBFFFF;

        .left {
            width: 120px;
            height: 120px;
            padding: 20px;

            .img {
                display: block;
                width: 120px;
                height: 120px;
            }
        }

        .mid {
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            margin-top: 18px;
            align-items: center;
            width: 300px;
            height: 120px;

            .name {
                font-size: 18px;
            }

            .author {
                span {
                    color: red;
                }
            }
        }

        .right {
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            margin-top: 18px;
            align-items: center;
            width: 300px;
            height: 120px;
        }
    }

    .empty {
        height: 280px;
        text-align: center;
        line-height: 280px;
        color: red;
        font-size: 18px;
    }
}
</style>